package net.pimpas.security.jaas.serviceprovider.auth.login;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Map;

import net.pimpas.security.jaas.serviceprovider.auth.JAASSubject;
import net.pimpas.security.jaas.serviceprovider.auth.login.callback.JAASCallbackHandler;
import net.pimpas.security.serviceprovider.auth.login.LoginException;
import net.pimpas.security.serviceprovider.auth.login.callback.Callback;
import net.pimpas.security.serviceprovider.auth.login.callback.UnsupportedCallbackException;

public abstract class JAASLoginModuleAbstract implements JAASLoginModule {
	
	private Boolean error;
	
	public JAASLoginModuleAbstract() {
		this.setError(Boolean.FALSE);
	}

	public void initialize(javax.security.auth.Subject subject, final javax.security.auth.callback.CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
		this.init(new JAASCallbackHandler() {
		
			@Override
			public void handle(Callback... callbacks) throws UnsupportedCallbackException, IOException,
					UnsupportedCallbackException {
				javax.security.auth.callback.Callback[] backs = new javax.security.auth.callback.Callback[callbacks.length];
				for(int i=0;i<backs.length;i++)
					backs[i] = (javax.security.auth.callback.Callback) callbacks[i];
				
				try {
					callbackHandler.handle(backs);
				} catch (javax.security.auth.callback.UnsupportedCallbackException e) {
					throw new UnsupportedCallbackException(e);
				}
			}
		}, new JAASSubject(subject), sharedState, options);
	}
	
	public boolean commit() throws LoginException, GeneralSecurityException {
		return !this.getError();
	}
	
	public boolean abort() throws LoginException, GeneralSecurityException {
		return this.getError();
	}

	public Boolean getError() {
		return error;
	}

	public void setError(Boolean error) {
		this.error = error;
	}
}